package me.thinkjet.sso.client.filter;

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.thinkjet.sso.client.util.CommonUtils;
import me.thinkjet.sso.client.util.HttpUtils;

public abstract class AbstractFilter extends AbstractConfigurationFilter {

	/**
	 * Represents the constant for where the assertion will be located in
	 * memory.
	 */
	public static final String CONST_SSO_ASSERTION = "_const_sso_assertion_";

	private String ticketName = "ticket";

	private String serviceName = "service";

	private boolean encodeServiceUrl = true;

	public final void init(final FilterConfig filterConfig)
			throws ServletException {
		if (!isIgnoreInitConfiguration()) {
			setTicketName(getPropertyFromInitParams(filterConfig, "ticketName",
					"ticket"));
			setServiceName(getPropertyFromInitParams(filterConfig,
					"serviceName", "service"));
			setEncodeServiceUrl(parseBoolean(getPropertyFromInitParams(
					filterConfig, "encodeServiceUrl", "true")));

			initInternal(filterConfig);
		}
		init();
	}

	protected void initInternal(final FilterConfig filterConfig)
			throws ServletException {
	}

	public void init() {
		CommonUtils
				.assertNotNull(this.ticketName, "ticketName cannot be null.");
		CommonUtils.assertNotNull(this.serviceName,
				"serviceName cannot be null.");
	}

	public void destroy() {
	}

	protected final String constructServiceUrl(
			final HttpServletRequest request, final HttpServletResponse response) {
		return HttpUtils.constructServiceUrl(request, response,
				this.ticketName, this.encodeServiceUrl);
	}

	public final void setTicketName(final String ticketName) {
		this.ticketName = ticketName;
	}

	public final void setServiceName(final String serviceName) {
		this.serviceName = serviceName;
	}

	public final void setEncodeServiceUrl(final boolean encodeServiceUrl) {
		this.encodeServiceUrl = encodeServiceUrl;
	}

	public final String getTicketName() {
		return this.ticketName;
	}

	public final String getServiceName() {
		return this.serviceName;
	}
}
